import http from 'node:http'
import url from 'node:url'
import fs from 'node:fs'
import path from 'node:path'
import {StringDecoder} from 'node:string_decoder'
import {deleteUser, getUserById, initDatabase, listUsers, listUsersPage, saveUser, User} from './crud.mjs'

const server = http.createServer((req, res) => {
    const decoder = new StringDecoder('utf-8')
    let buffer = ''

    req.on('data', (data) => {
        buffer += decoder.write(data)
    })

    req.on('end', () => {
        buffer += decoder.end()
        if (req.url === '/' && req.method === 'GET') {
            // index.html
            res.writeHead(200, {'Content-Type': 'text/html charset=utf-8'})
            res.end(fs.readFileSync(path.resolve(import.meta.dirname,'index.html')))
        } else {
            res.writeHead(200, {'Content-Type': 'application/json charset=utf-8'})
            if (req.url.startsWith('/get/') && req.method === 'GET') {
                // GET /get/:id
                const id = req.url.split('/')[2]
                res.end(JSON.stringify(getUserById(id)))
            } else if (req.url === '/list' && req.method === 'GET') {
                // GET /list
                res.end(JSON.stringify(listUsers()))
            } else if(req.url.startsWith('/page') && req.method === 'GET') {
                // GET /page?pageNum=1&pageSize=5
                const query = url.parse(req.url, true).query
                const page = listUsersPage(parseInt(query.pageNum), parseInt(query.pageSize))
                res.end(JSON.stringify(page))
            } else if (req.url === '/save' && req.method === 'POST') {
                // POST /save
                const user = JSON.parse(buffer)
                saveUser(new User(user.id, user.username, user.password))
                res.end(JSON.stringify({message: 'User saved successfully'}))
            } else if (req.url.startsWith('/del/') && req.method === 'DELETE') {
                // DELETE /del/:id
                const id = req.url.split('/')[2]
                deleteUser(id)
                res.end(JSON.stringify({message: 'User deleted successfully'}))
            } else {
                // Others response 404
                res.writeHead(404)
                res.end(JSON.stringify({msg: 'Not Found'}))
            }
        }
    })
})

server.listen(8080, () => {
    console.log('Server is running on http://localhost:8080')
    initDatabase()
})